<template>
    <div class="menu-manage">
        <div class="query-form">
            <el-form ref="menuFormRef" inline :model="menuSearch">
                <el-form-item label="菜单管理:" prop="menuName">
                    <el-input v-model="menuSearch.menuName" placeholder="请输入菜单管理"></el-input>
                </el-form-item>
                <el-form-item label="菜单状态:" prop="menuState">
                    <el-select v-model="menuSearch.menuState">
                        <el-option :value="1" :label="MenuState[1]"></el-option>
                        <el-option :value="2" :label="MenuState[2]"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="getMenuList" type="primary">查询</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-button @click="add(1)" v-HasPermission="'menu-create'" type="primary">创建</el-button>
            </div>
            <el-table row-key="menuId" :data="tableData.data" style="width:100%;">
                <el-table-column type="selection" width="55" />
                <el-table-column v-for="item in tableData.columns" :key="item.prop" :prop="item.prop"
                    :label="item.label" :width="item.width">
                    <template #default="scope" v-if="item.render">
                        <span>{{item.render ? item.render(scope.row,scope.column) : ''}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template #default="scope">
                        <el-button v-HasPermission="'menu-add'" type="primary" @click="add(2,scope.row)">新增</el-button>
                        <el-button v-HasPermission="'menu-edit'" @click="edit(scope.row)">编辑</el-button>
                        <el-button v-HasPermission="'menu-delete'" type="danger"
                            @click="singleRemove(scope.row.menuId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 编辑与新增 TO-DO -->
        <menu-form-dialog :parentId="formData.parentId" :type="action" :menuFormData="formData.menuFormData"
            :show="show" :title="formData.title" :menu="tableData.data as unknown[]" @close="close" @submit="submit">
        </menu-form-dialog>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { MenuState } from "@/utils/enum"
import type { FormInstance } from "element-plus"
import { Columns } from "@/interface/common"
import { MenuForm, MenuParams, MenuRow } from "@/interface/menu"
import { menuList } from "@/api/index"
import { menuCreate, menuEdit, menuDelete } from "@/api/menu"
import menuFormDialog from "./components/menuForm.vue"
import useCurrentInstance from "@/hook/useCurrentInstance"
import utils from "@/utils/utils.js"

onMounted(async () => {
    getMenuList()
})

// 查询条件
const menuFormRef = ref<FormInstance>()
const menuSearch = reactive<MenuParams>({
    menuName: "",
    menuState: 1
})
const reset = () => {
    menuFormRef.value!.resetFields()
}

// 列表
const tableData = reactive<Columns>({
    data: [],
    columns: [
        {
            label: "菜单名称",
            prop: "menuName",
            align: "center",
            width: 180
        },
        {
            label: '图标',
            prop: 'icon'
        },
        {
            label: '菜单类型',
            prop: 'menuType'
        },
        {
            label: '权限标识',
            prop: 'menuCode'
        },
        {
            label: '路由地址',
            prop: 'path'
        },
        {
            label: '组件路径',
            prop: 'component'
        },
        {
            label: '菜单状态',
            prop: 'menuState',
            render: (row, column) => {
                return MenuState[row.menuState]
            }
        },
        {
            label: '创建时间',
            prop: 'createTime',
            render: (row, column) => {
                return utils.formateDate(new Date(row.createTime))
            }
        }
    ]
})
// 获取列表数据
const getMenuList = async () => {
    try {
        const res = await menuList(menuSearch)
        console.log("数据", res);
        tableData.data = res.menuList
    } catch (error) {
        console.error(error)
    }
}

// 编辑与新增 TO-DO
const show = ref(false)
// 判断是编辑还是新增
const action = ref('add')
// 判断是直接点击左上角的创建还是列表数据后的新增 1为创建 2位新增或编辑
const haveParent = ref(1)
const formData = reactive({
    title: '创建菜单',
    menuFormData: {
        parentId: [""],
        menuType: 1,
        menuName: '',
        path: '',
        menuCode: '',
        menuState: 1
    },
    parentId: [] as string[]
})
// 创建
const add = (type: number, row?: MenuForm) => {
    haveParent.value = type
    formData.title = "新增菜单"
    action.value = "add"
    if (haveParent.value == 2) {
        // 将父级id，和自己id传递进去,将null过滤
        formData.parentId = [...JSON.parse(row!.parentId as unknown as string), row!.menuId].filter(item => item)
    }
    show.value = true
}
let timer: any = null;
// 编辑
const edit = (row: MenuRow) => {
    console.log("行数据", row)
    action.value = "edit"
    formData.title = "菜单编辑"
    console.log('编辑的parentId', formData.parentId)
    timer = setTimeout(() => {
        formData.parentId = [...JSON.parse(row!.parentId as unknown as string)].filter(item => item)
    }, 0)

    show.value = true

    // 防止数据被reset清除
    const data = Object.assign({}, row)
    formData.menuFormData = data
}
// 删除
const singleRemove = async (id: number) => {
    console.log(id)
    await menuDelete({ id })
    that.$message.success("删除成功")
    getMenuList()
}
const { globalProperties: that } = useCurrentInstance()
const submit = async (data: MenuForm) => {
    console.log('提交的数据', data)
    const params = { ...data }
    if (action.value === 'add') {
        const res = await menuCreate(params)
        that.$message.success("菜单添加成功")
        getMenuList()
        return
    }
    const res = await menuEdit(params)
    console.log('编辑', res)
    getMenuList()
    that.$message.success("菜单编辑成功")
}
const close = () => {
    show.value = false
    action.value = 'add'
    if (timer) {
        clearTimeout(timer)
    }
}
</script>
<style lang='scss' scoped>
.user-manage {
    width: 100%;
}
</style>